package com.jiangcheng.interceptor;

import com.jiangcheng.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * 类名称：TimeCostInterceptor<br>
 * 类描述：记录信息:</br> 访问时间</br>Controller路径</br>对应方法名</br>请求参数信息</br>请求相对路径</br>请求处理时长<br>
 * 创建时间：2018年09月11日<br>
 *
 * @author jiangcheng
 * @version 1.0.0
 */
@Slf4j
public class TimeCostInterceptor implements HandlerInterceptor {

    // before the actual handler will be executed


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime",startTime);
        if (handler instanceof HandlerMethod){
            StringBuilder sb = new StringBuilder(1000);
            sb.append("-----------------------").append(DateUtils.formatDateTime(new Date())).append("-------------------------------------\n");
            HandlerMethod h = (HandlerMethod) handler;
            sb.append("Controller: ").append(h.getBean().getClass().getName()).append("\n");
            sb.append("Method    : ").append(h.getMethod().getName()).append("\n");
            sb.append("Params    : ").append(getParamString(request.getParameterMap())).append("\n");
            sb.append("URI       : ").append(request.getRequestURI()).append("\n");
            log.info(sb.toString());
        }
        return true;
    }


    // after the handler is executed

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        long startTime = (Long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        long executeTime = endTime - startTime;
        if(handler instanceof HandlerMethod){
            StringBuilder sb = new StringBuilder(1000);
            sb.append("CostTime  : ").append(executeTime).append("ms").append("\n");
            sb.append("-------------------------------------------------------------------------------");
            log.info(sb.toString());
        }
    }

    private String getParamString(Map<String, String[]> map) {
        StringBuilder sb = new StringBuilder();
        for(Map.Entry<String,String[]> e:map.entrySet()){
            sb.append(e.getKey()).append("=");
            String[] value = e.getValue();
            if (e.getKey().equals("multipartFile")){
                sb.append("\t");
            } else if(value != null && value.length == 1){
                sb.append(value[0]).append("\t");
            } else {
                String content = Arrays.toString(value);
                if (content.length() > 12000){
                    content = content.substring(0,12000) + "...结果过长...";
                }
                sb.append(content).append("\t");
            }
        }
        return sb.toString();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //
    }
}
